using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Xml.Serialization;
using Caliburn.Micro;
using Action = System.Action;

namespace MediaOwl.Common.IsolatedStorage
{
    public class SerializeToIsolatedStorage : IResult
    {
        private readonly object instance;
        private readonly string fileName;
        private readonly Action onSuccess;
        private readonly Action<Exception> onFail;

        public SerializeToIsolatedStorage(object instance, string fileName, Action onSuccess  = null, Action<Exception> onFail = null)
        {
            this.instance = instance;
            this.fileName = fileName;
            this.onSuccess = onSuccess;
            this.onFail = onFail;
        }

        public void Execute(ActionExecutionContext context)
        {
            var t = instance.GetType();
            var serializer = new XmlSerializer(t);
            try
            {
                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    using (var isoStream = new IsolatedStorageFileStream(fileName, FileMode.Create, store))
                        serializer.Serialize(isoStream, instance);
                }
                if (onSuccess != null)
                    Caliburn.Micro.Execute.OnUIThread(() => onSuccess());
                Completed(this, new ResultCompletionEventArgs());
            }
            catch (Exception err)
            {
                if (onFail != null)
                    Caliburn.Micro.Execute.OnUIThread(() => onFail(err));
                Completed(this, new ResultCompletionEventArgs {Error = err});
            }
            
        }

        public event EventHandler<ResultCompletionEventArgs> Completed = delegate { };
    }
}